package com.xcf.codec;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xcf.model.RpcRequest;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * 解码器
 */
public class JsonDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int length = in.readableBytes();
        if (length >= 4) {
            in.markReaderIndex();
            int msgLength = in.readInt();
            byte[] data = new byte[msgLength];
            in.readBytes(data);
            RpcRequest rpcRequest = JSON.parseObject(data, RpcRequest.class);
            Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
            if (parameterTypes.length > 0) {
                Object[] parameters = rpcRequest.getParameters();
                for (int i = 0; i < parameterTypes.length; i++) {
                    if (parameters[i] != null && !(parameterTypes[i].isInstance(parameters[i]))) {
                        Object parameter = parameters[i];
                        if (parameter instanceof JSONObject) {
                            JSONObject obj = (JSONObject) parameter;
                            Object o = obj.toJavaObject(parameterTypes[i]);
                            parameters[i] = o;
                        }
                    }
                }
            }
            out.add(rpcRequest);
        }
    }
}
